<?php
/**
 * Export members list and offers / asks on pdf file
 *
 * @package    letsManager
 * @subpackage letsExport
 * @author     Jerome Fouilloy
 * @version    SVN: $Rev$
 */
class letsExportActions extends sfActions
{
  public function executeMembersToPdf(sfWebRequest $request)
  {
    $this->getResponse()->setContentType('application/pdf');
    
 /*   $cacheQuery = 'letsExport/membersToPdf';
    $cache = $this->getContext()->getViewCacheManager();
    if($cache != null && $cache->has($cacheQuery))
    {
      $this->getResponse()->setContent($cache->get($cacheQuery));
      return sfView::NONE;
    }*/
    $config = sfTCPDFPluginConfigHandler::loadConfig();
    // pdf object
    $pdf = new sfTCPDF();
    
    $assoId = $this->getUser()->getAssociationId();
    // get members
    $membersById = LetsMemberTable::getEnabledForAssociation($assoId,true,'username');
    $membersByName = LetsMemberTable::getEnabledForAssociation($assoId,true,'lastname');
    
    $this->getContext()->getConfiguration()->loadHelpers('Phone','Date');
    $assoName = AssociationTable::getById($this->getUser()->getAssociationId())->getName();
    $todayStr = date('d/m/Y');
    $assoMemberId = LetsConfiguration::memberIdForAssociation($assoId);

    // settings
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', '14'));
    $pdf->SetHeaderData('', 0, '', $assoName.' : Annuaire du '.$todayStr);
    $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // init pdf doc
    $pdf->AliasNbPages();
    $pdf->AddPage();

    // alternate between 2 colors the rows
    $rowColor1 = array(255,255,255);
    $rowColor2 = array(224,224,224);

    /*
     * 1: Create members list with phone number and email
     */
    // create header
    // set color for background
    $pdf->SetFillColor(0,0,0);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont("times", "", 10);

    $pdf->MultiCell(10, 0, 'Num', 1, 'C', 1, 0);
    $pdf->MultiCell(55, 0, 'Nom', 1, 'C', 1, 0);
    $pdf->MultiCell(25, 0, 'Téléphone 1', 1, 'C', 1, 0);
    $pdf->MultiCell(25, 0, 'Téléphone 2', 1, 'C', 1, 0);
    $pdf->MultiCell(0, 0, 'Email', 1, 'C', 1, 1);

    // end header
    // black text
    $pdf->SetTextColor(0,0,0);
    
  /*  $pdf->SetFillColor(25,25,25);
    $pdf->SetTextColor(255,255,255);
    
    
    $pdf->Cell(10,6,"Num",1,0,'C',1);
    $pdf->Cell(52,6,"Nom",1,0,'C',1);
    $pdf->Cell(32,6,"Tel1",1,0,'C',1);
    $pdf->Cell(32,6,"Tel2",1,0,'C',1);
    $pdf->Cell(62,6,"E-mail",1,0,'C',1);
    $pdf->Ln();
    
    $pdf->SetFillColor(235,235,235);
    $pdf->SetTextColor(0);
    $pdf->SetDrawColor(50,50,50);
    $pdf->SetLineWidth(0.2);  
    
    $pdf->SetWidths(array(10,52,32,32,62));
    $pdf->SetAligns(array('C','L','C','C','L'));
    $pdf->SetFills(array("D","D","D","D","D"));*/
    
    $numLine =1;
    $linePenalty = 0;
    foreach($membersById as $member)
    {
      // dont export association member
      if($member->getId() == $assoMemberId)
      {
        continue;
      }
      // 40 members by page
      if(($numLine +$linePenalty)% 40 == 0)
      {
        $pdf->AddPage();
      }
      if($numLine % 2 == 0)
      {
        $pdf->SetFillColorArray($rowColor1);
      }
      else{
        $pdf->SetFillColorArray($rowColor2);
      }
      $numMember = $member->getUsername();
      $name = $member->getLastname().' '.$member->getFirstname();
      $size_name = $pdf->GetStringWidth($name);
      $height_line =5;
      if($size_name >50)
      {
        $height_line =11;
        $linePenalty++;
      }
      
      $phoneHome = format_phonenumber($member->getPhoneHome());
      $phoneMobile = format_phonenumber($member->getPhoneMobile());
      $mail = $member->getEmail();

      $pdf->MultiCell(10, $height_line, $numMember, 1, 'C', 1, 0);
      $pdf->MultiCell(55, $height_line, $name, 1, 'L', 1, 0);
      $pdf->MultiCell(25, $height_line, $phoneHome, 1, 'C', 1, 0);
      $pdf->MultiCell(25, $height_line, $phoneMobile, 1, 'C', 1, 0);
      $pdf->MultiCell(0, $height_line, $mail, 1, 'L', 1, 1);
      
    //  $pdf->Row(array($numMember,$name,$phoneHome,$phoneMobile,$mail));
    //  $pdf->SetFills(array("FD","FD","FD","FD","FD"));

      $numLine++;
    }

    /*
     * 2: End first list and create members lsit with adress an city
     */
    $pdf->AddPage();
    // create header
    // set color for background
    $pdf->SetFillColor(0,0,0);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont("times", "", 10);

    
    $pdf->MultiCell(55, 0, 'Nom', 1, 'C', 1, 0);
    $pdf->MultiCell(10, 0, 'Num', 1, 'C', 1, 0);
    $pdf->MultiCell(75, 0, 'Adresse', 0, 'C', 1, 0);
    $pdf->MultiCell(12, 0, 'CP', 1, 'C', 1, 0);
    $pdf->MultiCell(0, 0, 'Ville', 1, 'C', 1, 1);

    // end header
    // black text
    $pdf->SetTextColor(0,0,0);
    
      //titre tableau 2*
   /* $pdf->SetFillColor(25,25,25);
    $pdf->SetTextColor(255,255,255);
    
    $pdf->Cell(50,6,"Nom",1,0,'C',1);
    $pdf->Cell(10,6,"Num",1,0,'C',1); 
    $pdf->Cell(80,6,"Adresse",1,0,'C',1);
    $pdf->Cell(12,6,"CP",1,0,'C',1);
    $pdf->Cell(38,6,"Ville",1,0,'C',1);
    $pdf->Ln();
    
    $pdf->SetFillColor(235,235,235);
    $pdf->SetTextColor(0);
    $pdf->SetWidths(array(50,10,78,12,40));
    $pdf->SetAligns(array('L','C','L','C','L'));
    $pdf->SetFills(array('D','D','D','D','D'));*/

    $numLine =1;
    $linePenalty =0;
    foreach($membersByName as $member)
    {
      // dont export association member
      if($member->getId() == $assoMemberId)
      {
        continue;
      }
      
      // 40 members by page
      if(($numLine + $linePenalty) % 40 == 0)
      {
        $pdf->AddPage();
      }
      if($numLine % 2 == 0)
      {
        $pdf->SetFillColorArray($rowColor1);
      }
      else{
        $pdf->SetFillColorArray($rowColor2);
      }
      $numMember = $member->getUsername();
      $name = $member->getLastname().' '.$member->getFirstname();
      if($member->getStreet2() != '' && $member->getStreet2() != null)
      {
        $adress = $member->getStreet() . ' - ' .$member->getStreet2();
      }
      else{
        $adress = $member->getStreet();
      }
      $zipcode = $member->getZipcode();
      $city = $member->getCity();
      
      $size_name = $pdf->GetStringWidth($name);
      $size_adress = $pdf->GetStringWidth($adress);
      $size_city = $pdf->GetStringWidth($city);
      $height_line =5;
      if($size_name >50 || $size_adress > 72 || $size_city > 35)
      {
        $height_line =11;
        $linePenalty++;
      }
      
      $pdf->MultiCell(55, $height_line, $name, 1, 'L', 1, 0);
      $pdf->MultiCell(10, $height_line, $numMember, 1, 'C', 1, 0);
      $pdf->MultiCell(75, $height_line, $adress, 1, 'L', 1, 0);
      $pdf->MultiCell(12, $height_line, $zipcode, 1, 'L', 1, 0);
      $pdf->MultiCell(0, $height_line, $city, 1,'L', 1, 1);
     // $pdf->Row(array($name,$numMember,stripslashes($adress),$zipcode,stripslashes($city)));
    //  $pdf->SetFills(array("FD","FD","FD","FD","FD"));

      $numLine++;
    }
    
    // output
    $pdf->Output('annuaire.pdf','I');
 /*   if($cache != null)
    {
      $cache->set($pdfContent,$cacheQuery);
    }
    $this->getResponse->setContent($pdfContent);*/
    // Stop symfony process
   // throw new sfStopException();
     return sfView::NONE;
  }

  public function executeAsksAndOffersToPdf(sfWebRequest $request)
  {
    $this->getResponse()->setContentType('application/pdf');
  /*  $cacheQuery = 'letsExport/asksAndOffersToPdf';
    $cache = $this->getContext()->getViewCacheManager();
    if($cache != null && $cache->has($cacheQuery))
    {
      $this->getResponse()->setContent(base64_decode($cache->get($cacheQuery)));
      return sfView::NONE;
    }*/
    $config = sfTCPDFPluginConfigHandler::loadConfig();
    // pdf object
    $pdf = new sfTCPDF();

    if($this->getUser()->isAuthenticated())
    {
      $assoId =$this->getUser()->getAssociationId();
    }
    else{
      $assoId =1;
    }
    $assoName = AssociationTable::getById($assoId)->getName();
    $todayStr = date('d/m/Y');
    // get asks
    $asks = LetsUserAskTable::getAllAksForAssociation($assoId);
    $offers = LetsUserOfferTable::getAllOffersForAssociation($assoId);

    $categoriesTmp = LetsMainCategoryTable::getQueryForAssociation($assoId)->execute();
    $categoriesName = array();
    foreach($categoriesTmp as $tmpCateg)
    {
      $categoriesName[intval($tmpCateg->getId())] = $tmpCateg->getName();
    }

    //$this->getContext()->getConfiguration()->loadHelpers('Date');

    // settings
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', '14'));
    $pdf->SetHeaderData('', 0, '', $assoName.' : Catalogue du '.$todayStr);
    $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // init pdf doc
    $pdf->AliasNbPages();
    $pdf->AddPage();

    // Create asks list
    self::generateListOffersOrAsks($pdf,$asks,$categoriesName,'Demandes');

    $pdf->AddPage();
    // create offers list
    self::generateListOffersOrAsks($pdf,$offers,$categoriesName,'Offres');
    
  /*  $pdfContent = $pdf->Output('annuaire.pdf','S');
    if($cache != null)
    {
      $cache->set(base64_encode($pdfContent),$cacheQuery);
    }
    $this->getResponse()->setContent($pdfContent);*/
    // output
    $pdf->Output('catalogue.pdf','I');
    // Stop symfony process
    //throw new sfStopException();
    return sfView::NONE;
  }
  private function telephoneFormat($tel){
      $temp=str_replace(" ","",trim($tel));
      if(strlen($temp)!=10) return "";
      $res="";
      for($z=0;$z<5;$z++){
        $res=$res.substr($temp,$z*2,2).".";
      }
      return(trim($res));
  }
  private static function generateListOffersOrAsks($pdf,$objects,$categoriesName,$title)
  {

    // alternate between 2 colors the rows
    $rowColor1 = array(255,255,255);
    $rowColor2 = array(224,224,224);

    // set color for background
    $pdf->SetFillColor(255, 255, 255);
    $pdf->SetTextColor(0,0,0);
    //
    $numLine =0;
    // current object row in category
    $numRow =0;
    $previousCategoryId = $objects[0]['category_id'];
    $linePenalty =0;
    foreach($objects as $obj)
    {
      // 40 by page
      if(($numLine+$linePenalty) % 40 == 0 && $numLine !=0)
      {
        $pdf->AddPage();
      }
      // first category or change category
      if($obj['category_id'] != $previousCategoryId || $numLine == 0)
      {
        $previousCategoryId = $obj['category_id'];
         
        $categName = 'Inconnu';
        if(isset($categoriesName[$previousCategoryId]))
        {
          $categName = $categoriesName[$previousCategoryId];
        }
         
        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetFont("times", "B", 14);
        $pdf->Cell(0,0,$title.' : '.$categName,1,1,'C');
        $numLine += 2;
        $numRow =0;
      }
      $pdf->SetFont("times", "", 10);
      if($numRow % 2 == 0)
      {
        $pdf->SetFillColorArray($rowColor1);
      }
      else{
        $pdf->SetFillColorArray($rowColor2);
      }
      $name = $obj['name'];
      $size_name = $pdf->GetStringWidth($name);
      $line_height =0;
      
      if($size_name > 165)
      {
        $line_height = 11;
        $linePenalty++;
      }
      
      $pdf->MultiCell(15, $line_height, $obj->getUser()->getUsername(), 1, 'C', 1, 0);
      $pdf->MultiCell(0, $line_height, $name, 1, 'L', 1, 1);

      $numLine++;
      $numRow++;
    }
  }


}
